using System.Windows.Input;
using HandyControl.Controls;
using HandyControl.Data;
using System;
using Infov1.Commands;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows;
using Infov1.Models;
using System.Xml.Linq;
using System.IO;

namespace Infov1.ViewModels
{
    public class MainViewModel : ViewModelBase
    {
        private readonly AdminModel _userModel;
        private string _username;
        private string _password;
        private bool _rememberPassword;  // 添加记住密码属性
        private const string configPath = "LoginInfo.xml";  // 配置文件路径

        public string Username
        {
            get => _username;
            set
            {
                _username = value;
                OnPropertyChanged();
            }
        }


        public string Password
        {
            get => _password;
            set
            {
                _password = value;
                OnPropertyChanged();
            }
        }

        // 添加记住密码绑定属性
        public bool RememberPassword
        {
            get => _rememberPassword;
            set
            {
                _rememberPassword = value;
                OnPropertyChanged();
            }
        }


        //加载动画
        private bool _isLoading;
        public bool IsLoading
        {
            get => _isLoading;
            set
            {
                _isLoading = value;
                OnPropertyChanged();
            }
        }
        public ICommand LoginCommand { get; }
        public ICommand MoveFocusCommand { get; }

        public MainViewModel()
        {
            LoginCommand = new RelayCommand(ExecuteLoginAsync);
            MoveFocusCommand = new RelayCommand<UIElement>(ExecuteMoveFocus);
            _userModel = new AdminModel();
            LoadLoginInfo(); // 加载保存的登录信息
        }
        // 加载保存的登录信息
        private void LoadLoginInfo()
        {
            try
            {
                if (File.Exists(configPath))
                {
                    var doc = XDocument.Load(configPath);
                    var root = doc.Root;
                    if (root != null)
                    {
                        var remember = bool.Parse(root.Element("remember")?.Value ?? "false");
                        if (remember)
                        {
                            Username = root.Element("username")?.Value ?? "";
                            //由于密码特殊性  这里不直接带出
                          /*  Password = root.Element("password")?.Value ;
                            System.Windows.MessageBox.Show(Password);*/
                            RememberPassword = true;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Growl.Error($"读取登录信息失败：{ex.Message}");
            }
        }

        private void ExecuteMoveFocus(UIElement element)
        {
            element?.Focus();
        }

        private async void ExecuteLoginAsync()
        {
            if (string.IsNullOrEmpty(Username) || string.IsNullOrEmpty(Password))
            {
                Growl.Warning(new GrowlInfo
                {
                    Message = "用户名和密码不能为空！",
                    ShowDateTime = false,
                    StaysOpen = false,
                    WaitTime = 2
                });
                return;
            }

            try
            {
                IsLoading = true; // 显示加载动画

                // 使用新的验证结果
                var result = await AdminModel.ValidateUserAsync(Username, Password);

                Application.Current.Dispatcher.Invoke(() =>
                {
                    if (result.IsValid)
                    {
                        // 如果勾选了记住密码，保存登录信息
                        if (RememberPassword)
                        {
                            SaveLoginInfo();
                        }

                        Growl.Success("登录成功！");

                        // 保存登录状态和管理员信息
                        Application.Current.Properties["IsLoggedIn"] = true;
                        Application.Current.Properties["Name"] = result.Name;
                        Application.Current.Properties["AdminName"] = _username;

                        // 导航到主页面
                        var IndexWindow = new Infov1.Views.IndexView();
                        IndexWindow.Show();

                        // 关闭登录窗口
                        foreach (HandyControl.Controls.Window window in Application.Current.Windows)
                        {
                            if (window is MainWindow)
                            {
                                window.Close();
                                break;
                            }
                        }
                    }
                    else
                    {
                        Growl.Error("用户名或密码错误！");
                    }
                });
            }
            catch (Exception ex)
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    Growl.Error($"登录失败：{ex.Message}");
                });
            }
            finally
            {
                IsLoading = false; // 隐藏加载动画
            }
        }
        // 保存登录信息
        private void SaveLoginInfo()
        {
            try
            {
                XDocument doc = new XDocument(
                    new XDeclaration("1.0", "utf-8", null),
                    new XElement("loginConfig",
                        new XElement("username", Username),
                        //new XElement("password", Password),
                        new XElement("remember", RememberPassword.ToString().ToLower())
                    )
                );
                doc.Save(configPath);
            }
            catch (Exception ex)
            {
                Growl.Error($"保存登录信息失败：{ex.Message}");
            }
        }
        // 简单的密码加密
        private string EncryptPassword(string password)
        {
            if (string.IsNullOrEmpty(password)) return "";
            return Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(password));
        }

        // 密码解密
        private string DecryptPassword(string encryptedPassword)
        {
            if (string.IsNullOrEmpty(encryptedPassword)) return "";
            try
            {
                byte[] bytes = Convert.FromBase64String(encryptedPassword);
                return System.Text.Encoding.UTF8.GetString(bytes);
            }
            catch
            {
                return "";
            }
        }
    }
} 